# _*_ coding : utf-8 _*_
# @Time : 2023/8/26 16:20
# @Author : 寻梦
# @File : 10_肯德基按城市名称爬取内容
# @Project : code
import json
import urllib.request
import urllib.parse

base_url="http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname"

def create_request(page,pagesize,city):
    data={
        "cname": city,
        "pid":'',
        "pageIndex": page,
        "pageSize": pagesize
    }
    request = urllib.request.Request(url=base_url,data=urllib.parse.urlencode(data).encode("utf8"),method="POST")
    return  request

def get_contentByRequest(request):
    response= urllib.request.urlopen(request)
    content=response.read().decode("utf8")
    return content

def download_res(content,flag):
    with open("data/kfc_"+str(flag)+".json",'w',encoding="utf8") as fp:
        fp.write(content)
        fp.close()

if __name__=="__main__":
    city=input("请输入要搜索的城市名称：")
    startPage=int(input("请输入开始搜索页："))
    endPage=int(input("请输入结束搜索页："))
    pageContent=0
    pagesize=10
    for page in range(startPage,endPage+1):
        if (page-1)*pagesize<=pageContent:
            request=create_request(page,pagesize,city)
            content=get_contentByRequest(request)
            pageContent=json.loads(content)["Table"][0]["rowcount"]
            download_res(content,page)